#! /usr/bin/env python
#coding=utf-8

import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../"))
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../../"))

import loader
from utils import ResterHelper
from utils import ResterStringBuilder

from .symbols import ElfSymbolRest

class DependencyRest(loader.Dependency, ResterStringBuilder):
	def __init__(self, row, mgr):
		loader.Dependency.__init__(self, row, mgr)

	def getDependSymbolsStr(self, cursor, args, mgr):
		return ResterHelper.build_array_content(self.getDependedSymbols(cursor, mgr, ElfSymbolRest), args)

	def getStr(self, xargs=None, extra_keys=None, extra_vals=None):
		keys = ("id", "caller.id", "callee.id", "caller.name", "callee.name", "calls")
		if xargs and "details" in xargs:
			keys = keys + ("callee.human_size", "callee.deps", "callee.deps_total", "callee.dependedBy")
		return ResterStringBuilder.getStr(self, xargs, keys, extra_vals)

class DepsRestMgr(object):
	def __init__(self, product):
		self._moduleMgr  = product.getMgr("modules")

	def doRestRequest(self, id, mod, args):
		mCmdMap = {
			'symbols':self._dbQuerySymbols
		}
		return mCmdMap[mod](id, args)

	def _dbQuerySymbols(self, id, args):
		dep = self._moduleMgr.get_dep_by_id(int(id))
		return dep.getDependSymbolsStr(self._moduleMgr.getCursor(), args, self._moduleMgr)

	def get_all(self, xargs):
		res = self._moduleMgr.get_all_deps()
		return [dep for dep in res if dep["chipsetsdk"]]
